var logManager=require("../Logs.js");
var ServerClient=require("./TcpSocketServerClient.js")
var SystemEvent=require("../event/SystemEvent")
var TCP = require('net');
var TcpSocketServer=Class.extend({
    name:"tcpSocket",
    socketCount:0,
    analysisClass:null,
    _port:0,
    _clientSocketDic:null,
    _serverSocket:null,
    eventManager:null,
    ctor(eventManager){
        this.eventManager=eventManager;
    },

    listen:function(port,analysisClass){
        this.analysisClass=analysisClass;
        this._port=port;
        this.close();
        this._clientSocketDic={};
        this._serverSocket=TCP.createServer();
        this._serverSocket.on("connection",this.addClientSocket.bind(this));
        this._serverSocket.listen(port);
        this.eventManager.addListener(SystemEvent.TCP_SOCKET_CLOSE,this.onSocketClose,this);
        logManager.logM("tcpsocket listen on:"+port)
    },
    close:function(){
        if(this._serverSocket)
            this._serverSocket.close();
        this._serverSocket=null;
        this.eventManager.removeListener(SystemEvent.TCP_SOCKET_CLOSE,this.onSocketClose,this);
    },
    onSocketClose:function(data){
        if(data.port!=this._port)return;
        if(this._clientSocketDic[data.clientId]) {
            delete this._clientSocketDic[data.clientId];
        }
    },
    closeSocketByClientId:function(clientId){
        if(this._clientSocketDic[clientId]) {
            var tem=this._clientSocketDic[clientId];
            delete this._clientSocketDic[clientId];
            tem.closeSocket();
        }
        // socketClient中有触发此事件
        // this.eventManager.dispatchEvent(SystemEvent.TCP_SOCKET_CLOSE,[{clientId:clientId,port:this._port}]);
    },
    addClientSocket:function (conn) {
        this.socketCount++;
        logManager.logM("add tcp socket client:"+this.socketCount)
        var client=new ServerClient(this.socketCount,conn,this._port,this.analysisClass,this.eventManager)
        this._clientSocketDic[this.socketCount]=client;
        this.eventManager.dispatchEvent(SystemEvent.TCP_SOCKET_ADD,[{clientId:this.socketCount,port:this._port}])
    },
    sendMsg:function (clientId,msg,data) {
        var client=this._clientSocketDic[clientId];
        if(client)
            client.sendMsg(msg,data);
    }
})

module.exports=TcpSocketServer